<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ETF历史净值数据（周度）</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .card {
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 25px rgba(0, 0, 0, 0.12);
        }
        .card-header {
            background-color: #007bff;
            color: white;
            border-radius: 12px 12px 0 0;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
        .btn-success {
            background-color: #28a745;
            border-color: #28a745;
        }
        .btn-success:hover {
            background-color: #1e7e34;
            border-color: #1e7e34;
        }
        .btn-danger {
            background-color: #dc3545;
            border-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
            border-color: #c82333;
        }
        .form-control:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
        .table {
            border-radius: 8px;
            overflow: hidden;
        }
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .table-hover tbody tr:hover {
            background-color: #f1f3f5;
        }
        .growth-positive {
            color: #dc3545;
            font-weight: 600;
        }
        .growth-negative {
            color: #28a745;
            font-weight: 600;
        }
        .growth-zero {
            color: #6c757d;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }
        .loading-spinner {
            width: 5rem;
            height: 5rem;
        }
        .chart-container {
            position: relative;
            height: 400px;
            margin: 20px 0;
        }
        .date-range-picker {
            display: flex;
            gap: 10px;
            align-items: end;
        }
        .date-range-picker .form-group {
            margin-bottom: 0;
            flex: 1;
        }
        .stat-card {
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 1rem;
        }
        .stat-card .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
        }
        .stat-card .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <!-- 加载遮罩层 -->
    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="spinner-border text-primary loading-spinner" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>

    <div class="container mt-5">
        <div class="row mb-4">
            <div class="col-lg-12">
                <h1 class="text-center mb-4">ETF历史净值数据（周度）</h1>
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">数据操作</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="fundCode">基金代码</label>
                                            <input type="text" class="form-control" id="fundCode" placeholder="请输入基金代码" value="510300">
                                        </div>
                                    </div>
                                    <div class="col-md-8 date-range-picker">
                                        <div class="form-group">
                                            <label for="startDate">开始日期</label>
                                            <input type="date" class="form-control" id="startDate" value="2023-01-01">
                                        </div>
                                        <div class="form-group">
                                            <label for="endDate">结束日期</label>
                                            <input type="date" class="form-control" id="endDate" value="2024-01-01">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 d-flex gap-2">
                                <button id="fetchBtn" class="btn btn-primary flex-grow-1 mt-4"><i class="fa fa-download mr-2"></i>抓取数据</button>
                                <button id="queryBtn" class="btn btn-success flex-grow-1 mt-4"><i class="fa fa-search mr-2"></i>查询数据</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计信息卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stat-card bg-primary text-white">
                    <div class="stat-label">平均单位净值</div>
                    <div class="stat-value" id="avgUnitNav">--</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card bg-success text-white">
                    <div class="stat-label">平均周增长率</div>
                    <div class="stat-value" id="avgGrowthRate">--</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card bg-info text-white">
                    <div class="stat-label">数据条数</div>
                    <div class="stat-value" id="dataCount">0</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card bg-warning text-white">
                    <div class="stat-label">时间跨度</div>
                    <div class="stat-value" id="timeSpan">--</div>
                </div>
            </div>
        </div>

        <!-- 图表展示 -->
        <div class="row mb-4">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">净值趋势图</h5>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="navChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据表格 -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">ETF周度历史净值数据</h5>
                        <div>
                            <button id="refreshBtn" class="btn btn-outline-primary btn-sm"><i class="fa fa-refresh mr-1"></i>刷新</button>
                            <button id="exportBtn" class="btn btn-outline-success btn-sm ml-2"><i class="fa fa-file-excel-o mr-1"></i>导出</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="dataTable" class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>基金代码</th>
                                        <th>净值日期</th>
                                        <th>单位净值</th>
                                        <th>累计净值</th>
                                        <th>周增长率</th>
                                        <th>周起始日期</th>
                                        <th>周结束日期</th>
                                        <th>申购状态</th>
                                        <th>赎回状态</th>
                                        <th>数据来源</th>
                                        <th>更新时间</th>
                                    </tr>
                                </thead>
                                <tbody id="dataTableBody">
                                    <!-- 数据将通过JavaScript动态填充 -->
                                    <tr>
                                        <td colspan="11" class="text-center">请输入基金代码并点击查询按钮获取数据</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    
    <script>
        // 全局变量
        let navChart = null;
        
        // 初始化页面
        $(document).ready(function() {
            // 设置默认结束日期为今天
            const today = new Date().toISOString().split('T')[0];
            $('#endDate').val(today);
            
            // 绑定事件
            $('#fetchBtn').click(fetchETFData);
            $('#queryBtn').click(queryETFData);
            $('#refreshBtn').click(queryETFData);
            $('#exportBtn').click(exportToExcel);
            
            // 初始化图表
            initChart();
        });
        
        // 显示加载遮罩
        function showLoading() {
            $('#loadingOverlay').show();
        }
        
        // 隐藏加载遮罩
        function hideLoading() {
            $('#loadingOverlay').hide();
        }
        
        // 初始化图表
        function initChart() {
            const ctx = document.getElementById('navChart').getContext('2d');
            navChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '单位净值',
                        data: [],
                        borderColor: '#007bff',
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        borderWidth: 2,
                        tension: 0.1,
                        fill: false
                    }, {
                        label: '累计净值',
                        data: [],
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        borderWidth: 2,
                        tension: 0.1,
                        fill: false
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': ' + context.parsed.y.toFixed(4);
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '日期'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '净值'
                            },
                            ticks: {
                                callback: function(value) {
                                    return value.toFixed(2);
                                }
                            }
                        }
                    }
                }
            });
        }
        
        // 更新图表数据
        function updateChart(dataList) {
            // 按日期排序
            dataList.sort((a, b) => new Date(a.navDate) - new Date(b.navDate));
            
            const labels = dataList.map(item => item.navDate);
            const unitNavData = dataList.map(item => parseFloat(item.unitNav));
            const cumulativeNavData = dataList.map(item => parseFloat(item.cumulativeNav));
            
            navChart.data.labels = labels;
            navChart.data.datasets[0].data = unitNavData;
            navChart.data.datasets[1].data = cumulativeNavData;
            navChart.update();
        }
        
        // 抓取ETF数据
        function fetchETFData() {
            const fundCode = $('#fundCode').val().trim();
            if (!fundCode) {
                alert('请输入基金代码');
                return;
            }
            
            showLoading();
            
            $.ajax({
                url: '/api/etfhist2/fetch',
                type: 'POST',
                data: { fundCode: fundCode },
                success: function(response) {
                    hideLoading();
                    if (response.status === 'success') {
                        alert('数据抓取成功');
                        queryETFData(); // 自动查询最新数据
                    } else {
                        alert('数据抓取失败: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    alert('请求失败: ' + error);
                }
            });
        }
        
        // 查询ETF数据
        function queryETFData() {
            const fundCode = $('#fundCode').val().trim();
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();
            
            if (!fundCode) {
                alert('请输入基金代码');
                return;
            }
            
            showLoading();
            
            $.ajax({
                url: '/api/etfhist2/byRange',
                type: 'GET',
                data: {
                    fundCode: fundCode,
                    startDate: startDate,
                    endDate: endDate
                },
                success: function(response) {
                    hideLoading();
                    if (response.status === 'success' && response.datas) {
                        renderDataTable(response.datas);
                        updateChart(response.datas);
                        updateStatistics(response.datas);
                    } else {
                        alert('查询失败: ' + (response.msg || '未知错误'));
                        clearDataTable();
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    alert('请求失败: ' + error);
                    clearDataTable();
                }
            });
        }
        
        // 渲染数据表格
        function renderDataTable(dataList) {
            const tbody = $('#dataTableBody');
            tbody.empty();
            
            if (!dataList || dataList.length === 0) {
                tbody.append('<tr><td colspan="11" class="text-center">暂无数据</td></tr>');
                return;
            }
            
            // 按日期降序排序
            dataList.sort((a, b) => new Date(b.navDate) - new Date(a.navDate));
            
            dataList.forEach(item => {
                const row = $('<tr></tr>');
                
                // 格式化增长率
                let growthRateClass = 'growth-zero';
                let growthRateValue = item.weeklyGrowthRate || '0.0000';
                if (parseFloat(growthRateValue) > 0) {
                    growthRateClass = 'growth-positive';
                } else if (parseFloat(growthRateValue) < 0) {
                    growthRateClass = 'growth-negative';
                }
                
                row.append(`
                    <td>${item.fundCode}</td>
                    <td>${item.navDate}</td>
                    <td>${item.unitNav || '--'}</td>
                    <td>${item.cumulativeNav || '--'}</td>
                    <td class="${growthRateClass}">${growthRateValue}%</td>
                    <td>${item.weekStartDate || '--'}</td>
                    <td>${item.weekEndDate || '--'}</td>
                    <td>${item.purchaseStatus || '--'}</td>
                    <td>${item.redemptionStatus || '--'}</td>
                    <td>${item.dataSource || '--'}</td>
                    <td>${formatDateTime(item.updateTime)}</td>
                `);
                
                tbody.append(row);
            });
            
            $('#dataCount').text(dataList.length);
        }
        
        // 清空数据表格
        function clearDataTable() {
            $('#dataTableBody').empty();
            $('#dataTableBody').append('<tr><td colspan="11" class="text-center">暂无数据</td></tr>');
            $('#dataCount').text('0');
            
            // 清空图表
            navChart.data.labels = [];
            navChart.data.datasets[0].data = [];
            navChart.data.datasets[1].data = [];
            navChart.update();
            
            // 清空统计信息
            $('#avgUnitNav').text('--');
            $('#avgGrowthRate').text('--');
            $('#timeSpan').text('--');
        }
        
        // 更新统计信息
        function updateStatistics(dataList) {
            if (!dataList || dataList.length === 0) {
                return;
            }
            
            // 计算平均单位净值
            const totalUnitNav = dataList.reduce((sum, item) => sum + (parseFloat(item.unitNav) || 0), 0);
            const avgUnitNav = totalUnitNav / dataList.length;
            $('#avgUnitNav').text(avgUnitNav.toFixed(4));
            
            // 计算平均周增长率
            const totalGrowthRate = dataList.reduce((sum, item) => sum + (parseFloat(item.weeklyGrowthRate) || 0), 0);
            const avgGrowthRate = totalGrowthRate / dataList.length;
            const growthRateClass = avgGrowthRate > 0 ? 'growth-positive' : avgGrowthRate < 0 ? 'growth-negative' : 'growth-zero';
            $('#avgGrowthRate').text(avgGrowthRate.toFixed(2) + '%').attr('class', 'stat-value ' + growthRateClass);
            
            // 计算时间跨度
            const dates = dataList.map(item => new Date(item.navDate)).sort((a, b) => a - b);
            const startDate = dates[0].toISOString().split('T')[0];
            const endDate = dates[dates.length - 1].toISOString().split('T')[0];
            $('#timeSpan').text(`${startDate} 至 ${endDate}`);
        }
        
        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '--';
            
            const date = new Date(dateTime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 导出Excel
        function exportToExcel() {
            const fundCode = $('#fundCode').val().trim();
            if (!fundCode) {
                alert('请先查询数据后再导出');
                return;
            }
            
            // 创建CSV内容
            let csvContent = '基金代码,净值日期,单位净值,累计净值,周增长率(%),周起始日期,周结束日期,申购状态,赎回状态,数据来源\n';
            
            $('#dataTableBody tr').each(function() {
                const rowData = [];
                $(this).find('td').each(function(index) {
                    // 跳过更新时间列
                    if (index < 10) {
                        let text = $(this).text().trim();
                        // 移除百分号
                        if (index === 4) {
                            text = text.replace('%', '');
                        }
                        rowData.push('"' + text + '"');
                    }
                });
                if (rowData.length > 0) {
                    csvContent += rowData.join(',') + '\n';
                }
            });
            
            // 创建Blob并下载
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            
            if (link.download !== undefined) {
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `ETF_${fundCode}_周度历史数据_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    </script>
</body>
</html>